package com.altekis.kanbankaze.server;

import java.util.Date;
import java.util.List;

import com.altekis.kanbankaze.client.TaskService;
import com.altekis.kanbankaze.server.dao.TaskDAO;
import com.altekis.kanbankaze.server.dao.UserStoryDAO;
import com.altekis.kanbankaze.shared.SerializableWhiteList;
import com.altekis.kanbankaze.shared.Task;
import com.altekis.kanbankaze.shared.TaskDTO;
import com.altekis.kanbankaze.shared.UserAccount;
import com.altekis.kanbankaze.shared.UserStory;
import com.altekis.kanbankaze.shared.events.CardUpdatedRemoteEvent;
import com.google.inject.Inject;

/**
 * The server side implementation of the {@link Task} RPC service.
 * 
 * @author gabriprat
 * 
 */
public class TaskServiceImpl implements TaskService {

	protected TaskDAO taskDAO;
	protected UserStoryDAO userStoryDAO;
	
	/**
	 * @param taskDAO
	 */
	@Inject
	public TaskServiceImpl(TaskDAO taskDAO, UserStoryDAO userStoryDAO) {
		this.taskDAO = taskDAO;
		this.userStoryDAO = userStoryDAO;
	}

	@Override
	public Task save(Task task) {
		task.setModificationDate(new Date());
		Task savedTask = taskDAO.save(task);
		// Preparamos un mensaje con la Task actualizada
		TaskDTO taskDTO = new TaskDTO(); // TODO Preparar un transformer?
		taskDTO.setId(task.getId());
		taskDTO.setName(task.getName());
		CardUpdatedRemoteEvent event = new CardUpdatedRemoteEvent();
		event.taskDTO = taskDTO;
		//TaskUpdatedMessage message = new TaskUpdatedMessage(taskDTO);
		// Ademas de grabar la tarea, enviaremos mensaje de actualizacion al resto de clientes
		for (UserAccount user: TemporaryRepository.users) {
			//ChannelServer.sendMessage(user.getLogin(), message);
			ChannelServer.sendTrojanMessage(user.getLogin(), event);
		}
		return savedTask;
	}

	@Override
	public List<Task> findAll() {
		List<Task> ret = taskDAO.findAll();
		return ret;
	}

	@Override
	public List<Task> findNewer(Date minDate) {
		List<Task> ret = taskDAO.findNewer(minDate);
		return ret;
	}

	@Override
	public List<UserStory> findAllUserStories() {
		List<UserStory> ret = userStoryDAO.findAll();
		return ret;
	}

	/**
	 * Implementation of fake method to force serialization of classes
	 */
	@Override
	public SerializableWhiteList fakeMethod(SerializableWhiteList l) { return null; }
}
